Popular Searches
Popular Course Categories
Popular Courses

Dart Loops

Dart Basics

Dart Loops

Loops are one of the most important concepts in Dart programming. A loop allows you to execute the same block of code repeatedly while a particular condition is satisfied or while items remain in a collection.

Loops are especially useful in Flutter applications for processing lists of products, displaying users, generating repeated UI-related data, performing calculations, validating information, and working with collections.

JustAcademy's Flutter curriculum includes Dart Programming Fundamentals, where control statements such as loops and switch are covered along with variables, data types, operators, functions, OOP, collections, and asynchronous programming. :contentReference[oaicite:0]{index=0}

1. What Is a Loop?

A loop is a programming structure that repeatedly executes a block of code.

For example, instead of writing:

print("Hello");
print("Hello");
print("Hello");
print("Hello");
print("Hello");

You can use a loop:

for (int i = 1; i <= 5; i++) {
  print("Hello");
}

The loop executes the print() statement five times.

2. Why Are Loops Used?

Loops are useful when the same operation needs to be performed multiple times.

  • Printing numbers
  • Processing lists
  • Searching for data
  • Calculating totals
  • Displaying collection items
  • Repeating a task until a condition changes
  • Processing API or database results
  • Generating repeated application data
  • Working with Flutter lists and collections

3. Types of Loops in Dart

Dart provides several commonly used looping techniques:

  1. for loop
  2. while loop
  3. do-while loop
  4. for-in loop
  5. forEach() method for collections

4. for Loop

The for loop is commonly used when you know how many times a block of code should execute or when you need a counter.

Syntax

for (initialization; condition; increment/decrement) {
  // code to execute
}

Example

for (int i = 1; i <= 5; i++) {
  print(i);
}

Output:

1
2
3
4
5

5. Understanding the for Loop

Consider:

for (int i = 1; i <= 5; i++) {
  print(i);
}

The three parts are:

Part Code Purpose
Initialization int i = 1 Creates and initializes the counter
Condition i <= 5 Determines whether the loop continues
Update i++ Changes the counter after each iteration

6. Printing Numbers Using for

for (int i = 1; i <= 10; i++) {
  print(i);
}

7. Printing Even Numbers

for (int i = 2; i <= 20; i += 2) {
  print(i);
}

Output:

2
4
6
8
10
12
14
16
18
20

8. Printing Odd Numbers

for (int i = 1; i <= 20; i += 2) {
  print(i);
}

9. Reverse for Loop

A for loop can also run in reverse.

for (int i = 10; i >= 1; i--) {
  print(i);
}

Output:

10
9
8
7
6
5
4
3
2
1

10. Calculating a Sum Using for

int sum = 0;

for (int i = 1; i <= 10; i++) {
  sum += i;
}

print("Sum = $sum");

Output:

Sum = 55

11. Multiplication Table Using for

int number = 5;

for (int i = 1; i <= 10; i++) {
  print("$number x $i = ${number * i}");
}

Output:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

12. while Loop

The while loop repeatedly executes code as long as its condition remains true.

Syntax

while (condition) {
  // code
}

Example

int i = 1;

while (i <= 5) {
  print(i);
  i++;
}

Output:

1
2
3
4
5

13. How a while Loop Works

The execution process is:

  1. Initialize a variable.
  2. Check the condition.
  3. If the condition is true, execute the loop body.
  4. Update the variable.
  5. Check the condition again.
  6. Repeat until the condition becomes false.

Example

int count = 1;

while (count <= 3) {
  print("Count: $count");
  count++;
}

14. Important Point About while

Make sure the condition eventually becomes false. Otherwise, you may accidentally create an infinite loop.

Incorrect example:

int i = 1;

while (i <= 5) {
  print(i);
}

Here, i is never changed, so the condition remains true.

Correct version:

int i = 1;

while (i <= 5) {
  print(i);
  i++;
}

15. do-while Loop

The do-while loop is similar to the while loop, but the loop body executes at least once before the condition is checked.

Syntax

do {
  // code
} while (condition);

Example

int i = 1;

do {
  print(i);
  i++;
} while (i <= 5);

16. do-while Executes at Least Once

Consider this example:

int number = 10;

do {
  print("Number: $number");
  number++;
} while (number < 5);

Even though number < 5 is false, the message is printed once because the condition is checked after the loop body.

17. for-in Loop

The for-in loop is particularly useful when working with collections such as Lists, Sets, and other iterable data.

Syntax

for (variable in collection) {
  // code
}

Example with List

List fruits = ["Apple", "Banana", "Mango"];

for (String fruit in fruits) {
  print(fruit);
}

Output:

Apple
Banana
Mango

18. for-in with Numbers

List numbers = [10, 20, 30, 40, 50];

for (int number in numbers) {
  print(number);
}

19. for-in with Set

Set cities = {
  "Mumbai",
  "Delhi",
  "Pune",
  "Bangalore"
};

for (String city in cities) {
  print(city);
}

20. for-in with Map

A Map contains key-value pairs. You can iterate through its entries using entries.

Map marks = {
  "Rahul": 85,
  "Amit": 90,
  "Priya": 92
};

for (var entry in marks.entries) {
  print("${entry.key}: ${entry.value}");
}

21. forEach() Method

Dart collections also provide the forEach() method for executing a function for each item.

List names = ["Rahul", "Amit", "Priya"];

names.forEach((name) {
  print(name);
});

Using Arrow Function

List names = ["Rahul", "Amit", "Priya"];

names.forEach((name) => print(name));

22. for Loop vs for-in Loop

for Loop for-in Loop
Uses a counter or index Directly accesses each collection item
Useful when the index is required Useful when only the item is required
More control over iteration Cleaner for collection traversal
Example: i++ Example: for (item in items)

23. Accessing List Index with for

If you need both the index and the value, a traditional for loop can be useful.

List fruits = ["Apple", "Banana", "Mango"];

for (int i = 0; i < fruits.length; i++) {
  print("Index $i: ${fruits[i]}");
}

Output:

Index 0: Apple
Index 1: Banana
Index 2: Mango

24. break Statement

The break statement immediately terminates the loop.

for (int i = 1; i <= 10; i++) {
  if (i == 6) {
    break;
  }

  print(i);
}

Output:

1
2
3
4
5

25. continue Statement

The continue statement skips the current iteration and moves to the next iteration.

for (int i = 1; i <= 5; i++) {
  if (i == 3) {
    continue;
  }

  print(i);
}

Output:

1
2
4
5

26. break vs continue

Statement Purpose
break Stops the entire loop
continue Skips the current iteration

27. Nested Loops

A loop inside another loop is called a nested loop.

for (int i = 1; i <= 3; i++) {
  for (int j = 1; j <= 3; j++) {
    print("i = $i, j = $j");
  }
}

Nested loops are useful for working with grids, tables, matrices, and multi-dimensional data.

28. Multiplication Tables Using Nested Loops

for (int i = 1; i <= 3; i++) {
  for (int j = 1; j <= 10; j++) {
    print("$i x $j = ${i * j}");
  }

  print("--------------");
}

29. Looping Through a List of Products

List products = [
  "Laptop",
  "Mobile",
  "Tablet",
  "Headphones"
];

for (String product in products) {
  print("Product: $product");
}

30. Calculating Total Price

List prices = [100.0, 250.0, 75.0, 300.0];

double total = 0;

for (double price in prices) {
  total += price;
}

print("Total = ₹$total");

31. Finding the Largest Number

List numbers = [10, 45, 23, 89, 12];

int largest = numbers[0];

for (int number in numbers) {
  if (number > largest) {
    largest = number;
  }
}

print("Largest number: $largest");

32. Searching for an Item

List products = [
  "Laptop",
  "Mobile",
  "Tablet",
  "Monitor"
];

String searchItem = "Tablet";
bool found = false;

for (String product in products) {
  if (product == searchItem) {
    found = true;
    break;
  }
}

if (found) {
  print("Product found");
} else {
  print("Product not found");
}

33. Counting Even Numbers

List numbers = [10, 15, 20, 25, 30, 35];

int count = 0;

for (int number in numbers) {
  if (number % 2 == 0) {
    count++;
  }
}

print("Even numbers: $count");

34. Processing Student Marks

List marks = [85, 72, 90, 64, 45];

for (int mark in marks) {
  if (mark >= 80) {
    print("$mark - Excellent");
  } else if (mark >= 60) {
    print("$mark - Good");
  } else if (mark >= 40) {
    print("$mark - Pass");
  } else {
    print("$mark - Fail");
  }
}

35. Loops in Flutter Applications

Loops are useful in Flutter when processing application data such as products, users, messages, categories, or other collections. JustAcademy's Flutter training covers Flutter and Dart, UI development, API integration, Firebase, database handling, state management, testing, deployment, and practical projects. :contentReference[oaicite:1]{index=1}

Example: Product Data

List products = [
  "Laptop",
  "Smartphone",
  "Tablet",
  "Smart Watch"
];

for (String product in products) {
  print(product);
}

36. Looping Through User Data

List> users = [
  {
    "name": "Rahul",
    "age": 25
  },
  {
    "name": "Priya",
    "age": 28
  },
  {
    "name": "Amit",
    "age": 22
  }
];

for (var user in users) {
  print("${user["name"]} - ${user["age"]}");
}

37. Choosing the Right Loop

Loop When to Use
for When you need a counter, index, or controlled number of iterations
while When repetition depends primarily on a condition
do-while When the code must execute at least once
for-in When iterating directly through collection values
forEach() When applying a function to each collection element

38. Common Loop Mistakes

Mistake 1: Infinite Loop

int i = 1;

while (i <= 5) {
  print(i);
}

The variable is never updated, so the loop does not reach its stopping condition.

Mistake 2: Incorrect Loop Condition

for (int i = 1; i > 10; i++) {
  print(i);
}

The condition is false from the beginning, so the loop does not execute.

Mistake 3: Wrong List Index

List names = ["A", "B", "C"];

for (int i = 0; i <= names.length; i++) {
  print(names[i]);
}

The condition should normally be i < names.length, because the last valid index is length - 1.

Correct version:

for (int i = 0; i < names.length; i++) {
  print(names[i]);
}

39. Best Practices for Loops

  • Use the simplest loop that matches your requirement.
  • Always make sure loop conditions can eventually become false.
  • Use for-in when you only need collection values.
  • Use a traditional for loop when you need indexes.
  • Use break when searching and you have found the required item.
  • Use continue when certain iterations should be skipped.
  • Avoid unnecessarily complicated nested loops.
  • Use meaningful variable names.
  • Be careful with collection indexes and boundaries.

40. Complete Dart Loop Example

void main() {
  List numbers = [10, 20, 30, 40, 50];

  int total = 0;

  for (int number in numbers) {
    total += number;
  }

  print("Total: $total");

  int i = 1;

  while (i <= 3) {
    print("While loop: $i");
    i++;
  }

  int count = 1;

  do {
    print("Do-while: $count");
    count++;
  } while (count <= 3);

  for (int number in numbers) {
    if (number == 30) {
      print("30 found");
      break;
    }
  }
}

41. Quick Revision

Concept Purpose
for Repeats code using initialization, condition, and update
while Repeats while a condition is true
do-while Executes at least once before checking the condition
for-in Iterates directly over collection elements
forEach() Runs a function for each collection item
break Stops the loop
continue Skips the current iteration

42. Practice Exercises

  1. Print numbers from 1 to 100 using a for loop.
  2. Print all even numbers from 1 to 50.
  3. Print all odd numbers from 1 to 50.
  4. Print numbers from 10 to 1 in reverse order.
  5. Calculate the sum of numbers from 1 to 100.
  6. Create a multiplication table using a for loop.
  7. Use a while loop to print numbers from 1 to 10.
  8. Use a do-while loop to print numbers from 1 to 5.
  9. Use a for-in loop to print all items in a List.
  10. Find the largest number in a List.
  11. Find the smallest number in a List.
  12. Count the number of even values in a List.
  13. Search for a particular product in a List.
  14. Use break to stop searching after finding an item.
  15. Use continue to skip a particular number.
  16. Create a nested loop to print a number pattern.

43. Key Takeaways

  • Loops are used to repeat a block of code.
  • The for loop is useful when you need controlled iteration or an index.
  • The while loop continues while a condition is true.
  • The do-while loop executes its body at least once.
  • The for-in loop is convenient for iterating over collection values.
  • forEach() can execute a function for every collection element.
  • break terminates a loop.
  • continue skips the current iteration.
  • Loops are widely used when processing collections and application data in Dart and Flutter.

44. Learn Flutter with JustAcademy

JustAcademy's current Flutter course includes Dart programming fundamentals with variables, data types, operators, control statements including loops and switch, functions and parameters, OOP, collections, and asynchronous programming. :contentReference[oaicite:2]{index=2}

Explore the complete Flutter course: JustAcademy Flutter Training

Register for a course demo: JustAcademy Course Demo Registration

whatsapp